package net.toocruel.iqismart.service.exception;

import net.sf.json.JSONObject;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.util.List;
import java.util.Map;

/**
 * @Description
 * @Auther sty
 * @createTime 2018/5/5 下午11:56
 */
public class BusinessException extends RuntimeException{
    protected String field = "";
    public JSONObject fields = new JSONObject();
    protected List<FieldError> fieldErrors;

    public BusinessException(String message) {
        super(message);
    }

    public static BusinessException with(BindingResult bindingResult) {
        BusinessException businessException = new BusinessException("");
        if(bindingResult.hasErrors()){
            Map<String, Object> model = bindingResult.getModel();
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            for(int i=0;i<fieldErrors.size();i++){
                FieldError fieldError = fieldErrors.get(i);
                if(businessException.getFields().get(fieldError.getField())!=null) {
                    businessException.getFields().put(fieldError.getField(),businessException.getFields().optString(fieldError.getField())+"<br>" +fieldError.getDefaultMessage());
                }else {
                    businessException.getFields().put(fieldError.getField(), fieldError.getDefaultMessage());
                }
            }

        }
        return businessException;

    }



    public BusinessException(List<FieldError> fieldErrors) {
       this.fieldErrors = fieldErrors;
    }

    public BusinessException(String field,String message) {
        super(message);
        this.field =field;
        this.fields.put(field,message);
    }


    public String getField() {
        return field;
    }

    public void setField(String field) {
        this.field = field;
    }

    public JSONObject getFields() {
        return fields;
    }

    public void setFields(JSONObject fields) {
        this.fields = fields;
    }

    public List<FieldError> getFieldErrors() {
        return fieldErrors;
    }

    public void setFieldErrors(List<FieldError> fieldErrors) {
        this.fieldErrors = fieldErrors;
    }
}
